package com.kayt.cyberBar.common.utils;

import java.util.Random;

/**
 * 随机串
 */
public class RandomUtil {

	public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static final String NUMBERCHAR = "0123456789";
	private static Random random = new Random();

	/**
	 *  生成一个长度为length、内容为charAt的随机字符串
	 * @param charAt 要生成的字符串包含的内容，如：ALLCHAR、LETTERCHAR、NUMBERCHAR
	 * @param length 生成字符串长度
	 * @return 返回数据
	 */
	public static String generateRandomString(String charAt, int length) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			sb.append(charAt.charAt(random.nextInt(charAt.length())));
		}
		return sb.toString();
	}
	public static String generateNumStr(int length){
	  return generateRandomString(NUMBERCHAR,length);
	}


	/**
	 *
	 * 生成一个长度为length；内容为ch的字符串
	 * @param ch 生成的内容
	 * @param length
	 *            字符串长度
	 * @return  返回串
	 */
	public static String generateZeroString(char ch,int length) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			sb.append(ch);
		}
		return sb.toString();
	}

	/**
	 * 根据数字生成一个定长的字符串，长度不够前面补0
	 * 
	 * @param num
	 *            数字
	 * @param fixdlenth
	 *            字符串长度
	 * @return 定长的字符串
	 */
	public static String toFixdLengthString(long num, int fixdlenth) {
		StringBuffer sb = new StringBuffer();
		String strNum = String.valueOf(num);
		if (fixdlenth - strNum.length() >= 0) {
			sb.append(generateZeroString('0',fixdlenth - strNum.length()));
		} else {
			throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth
					+ "的字符串发生异常！");
		}
		sb.append(strNum);
		return sb.toString();
	}
	
}
